package cn.uway.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TcpServer extends Thread {
	
	private static Logger logger = LoggerFactory.getLogger(TcpServer.class);
	
    private  int  port;
	
	public TcpServer(int port){
		this.port = port;
	}	
	
	public  void  run(){
		   try {
			    this.bind(port);
		   } 
		   catch (Exception e) {
			   logger.error("启动  TcpServer:" +port+ "失败", e);	
		   }
	}    
	 
	private void bind(int port) throws Exception { 
		    logger.debug("TcpServer started...port={}", port);
	        ////配置服务端的NIO线程组  
	        EventLoopGroup bossGroup = new NioEventLoopGroup();  
	        EventLoopGroup workerGroup = new NioEventLoopGroup();  
	        try {  
	            ServerBootstrap b = new ServerBootstrap();  
	            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)  
	                    .childHandler(new ChannelInitializer<SocketChannel>() {  
	                                @Override  
	                                public void initChannel(SocketChannel ch) throws Exception {  
	                                    ch.pipeline().addLast(new ServerChannelHandler());  
	                                }  
	                            }).option(ChannelOption.SO_BACKLOG, 12800) //最大客户端连接数为12800  
	                    .childOption(ChannelOption.SO_KEEPALIVE, false);  
	            //绑定端口，同步等待成功  
	            ChannelFuture f = b.bind(port).sync();  
	            logger.debug("===========已开启TCP服务端口:{}", port);
	            //等待服务端监听端口关闭  
	            f.channel().closeFuture().sync();  
	        } 
	        finally {  
	            //优雅退出，释放线程池资源  
	            workerGroup.shutdownGracefully();  
	            bossGroup.shutdownGracefully();  
	        }  
	        
	  }


		
}
